package cn.zjj.service.impl;

import cn.zjj.domain.MovieTicket;
import cn.zjj.dto.UserTicketDto;
import cn.zjj.enums.GlobalErrorCode;
import cn.zjj.exception.GlobalCustomException;
import cn.zjj.mapper.MovieTicketMapper;
import cn.zjj.service.IMovieTicketService;
import cn.zjj.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MovieTicketServiceImpl implements IMovieTicketService {
    @Autowired
    private MovieTicketMapper movieTicketMapper;


    @Override
    public void buyTicket(UserTicketDto buyTicketDto) {
        Long movieTicketId = buyTicketDto.getMovie_ticket_id();
        MovieTicket movieTicket = selectById(movieTicketId);
        Integer stock = movieTicket.getStock();
        Date start_time = movieTicket.getStart_time();
        if(start_time.getTime()<System.currentTimeMillis() || stock<0){
            throw new GlobalCustomException(GlobalErrorCode.MOVIETICKET_IS_NULL_ERROR);
        }
        movieTicket.setStock(movieTicket.getStock()-1);
        movieTicketMapper.update(movieTicket);
        builderMoverUserRole(buyTicketDto);
    }

    private void builderMoverUserRole(UserTicketDto buyTicketDto) {
        movieTicketMapper.insertMoverUserRole(buyTicketDto);
    }

    @Override
    public MovieTicket selectById(Long id) {
        return movieTicketMapper.selectById(id);
    }

    @Override
    public List<MovieTicket> select() {
        return movieTicketMapper.select();
    }

    @Override
    public MovieTicket selectUserTicket(UserTicketDto userTicketDto) {
        //当前用户拥有的电影票
        UserTicketDto movieUserRole = movieTicketMapper.selectUserTicket(userTicketDto);
        AssertUtil.isNotNull(movieUserRole,GlobalErrorCode.MOVIETICKET_IS_NOT_HAVE_ERROR);//提示未拥有
        //根据电影票id查询
        MovieTicket movieTicket = selectById(userTicketDto.getMovie_ticket_id());
        if(movieTicket.getStart_time().getTime()-System.currentTimeMillis()<0){
            throw new GlobalCustomException(GlobalErrorCode.MOVIETICKET_IS_OVERDUE_ERROR);//提示过期
        }
        if(movieUserRole.getStatus()==1){
            throw new GlobalCustomException(GlobalErrorCode.MOVIETICKET_IS_USE_ERROR);//提示已使用
        }
        movieTicketMapper.updateUserTicket(userTicketDto);
        return movieTicket;
    }

    //查询所有未开播的电影id
    @Override
    public List<Long> getAllId() {
        return movieTicketMapper.selectAllId();
    }
}
